$(document).ready(init);
function init () {
	$('#post-form').on('submit', post);
	//$('#postyardsale').click(post);
	//get current address
	$('#post-current').click(getCurrentAddress);
	//show popup post
	if($('#feedback').length){
		$('#btn-feedback').click(function(){
			$('#feedback').show();
			$('#feedback').height($('body').height());
			datetime();
		})
		$('.close').click(function(){
			$('#feedback').hide();
			datetime();
		});
	}

	if($('#post').length){
		$('#post').click(function(){
			$('#box').show();
			$('#box').height($('body').height());
			datetime();
		});
		$('#postsale').click(function(){
			$('#box').show();
			$('#box').height($('body').height());
			datetime();
		})
		$('.close').click(function(){
			$('#box').hide();
			datetime();
		});
	}
	//show popup login
	if($('#login').length){
		$('#login').click(function(){
			$('#box').show();
			$('#box').height($('body').height());
			datetime();
		})
		$('.close').click(function(){
			$('#box').hide();
			datetime();
		});
	}
	//show popup register
	if($('#register').length){
		$('#register').click(function(){
			$('#popup-register').show();
			$('#popup-register').height($('body').height());
			datetime();
		})
		$('.close').click(function(){
			$('#popup-register').hide();
			datetime();
		});
	}
	$('#list-items').find('.close').click(function(){
		$('#list-items').hide();
	});
	//load more
	//loadMore();
	if($('#saveChange').length){
		$('#saveChange').click(saveProfile);
	}
}

function saveProfile(){
	var first_name = $('#profile_first_name').val();
	var last_name = $('#profile_last_name').val();
	var email = $('#profile_email').val();
	var address = $('#profile_address').val();
	if(first_name == ''){
		alert('First name is not empty');
		$('#profile_first_name').focus();
		return false;
	}else if(last_name == ''){
		alert('Last name is not empty');
		$('#profile_last_name').focus();
		return false;
	}else if(email == ''){
		alert('Email is not empty');
		$('#profile_email').focus();
		return false;
	}else if(email !== '' && !checkMail(email)){
		alert('Email is not correct');
		$('#profile_email').focus();
		return false;
	}
	$.ajax({
		url: 'profile/updateinfo',
		type: 'post',
		data: {first_name: first_name, last_name: last_name, email: email, address: address},
		dataType: 'json',
		beforeSend: function(){

		},
		success: function(data){
			if(data == 1){
				alert('Your information is updated!');
				location.href = '/profile.html';
			}
		}
	});
}

function loadMore(){
    var track_load = 0; //total loaded record group(s)
    var loading  = false; //to prevents multipal ajax loads

    
    $('#loadmore').load("site/loadmore", {'page':track_load}, function() {track_load++;}); //load first group
    
    $('#loadmore').click(function() { 

        if($('#loadmore').scrollTop() + $('#loadmore').height() == $(document).height())  //user scrolled to bottom of the page?
        {
            
            if(track_load <= total_groups && loading==false) //there's more data to load
            {
                loading = true; //prevent further ajax loading
                //$('.animation_image').show(); //show loading image
                
                //load data from the server using a HTTP POST request
                $.post('site/loadmore',{'group_no': track_load}, function(data){
                                    
                    $("#loadmore").append(data); //append received data into the element

                    //hide loading image
                    //$('.animation_image').hide(); //hide loading image once data is received
                    
                    track_load++; //loaded group increment
                    loading = false; 
                
                }).fail(function(xhr, ajaxOptions, thrownError) { //any errors?
                    
                    alert(thrownError); //alert with HTTP error
                    //$('.animation_image').hide(); //hide loading image
                    loading = false;
                
                });
                
            }
        }
    });
}
function fb_login(){
    FB.login(function(response) {
		if (response.authResponse) {
			alert(response.authResponse)
	    	getUserInfo(response.authResponse);
	    } else{

	    	console.log('User cancelled login or did not fully authorize.');
	    }
    },{scope: 'user_photos, user_birthday, email, publish_actions', photo_upload: true});
}

function getUserInfo(authResponse) {  
    var me = []
    FB.api('/me/picture?type=normal', function(response){
    	me['photo'] = response.data.url;
        //console.log(me)
    });
                
	FB.api('/me', function(response) {
    	me['email'] = response.email;
        me['first_name'] = response.first_name;
        me['last_name'] = response.last_name;
        me['gender'] = response.gender;
        me['id'] = response.id;
        me['access_token'] = authResponse.accessToken;
        $.ajax({
        	url: 'fbinfo',
            data:{
                'email': response.email,
                'first_name': response.first_name,
                'last_name': response.last_name,
                'gender': response.gender,
                'id': response.id,
                'access_token': authResponse.accessToken,
                'photo': me['photo']
            },
            beforeSend:function(){
                            
            },
            type:'post',
            dataType:'json',
            success: function(data){
            	$('#popup-login').hide()
            }
		});
    });
}
           
function fb_logout() {
	FB.logout(function(response) {
    	console.log('Logout thành công');
    });
}

function post(e){
	e.preventDefault();
    var formData = new FormData($(this)[0]);

	var title = $('#post-title').val();
	var content = $('#post-content').val();
	//var current_address = $('#post-current-address').val();
	var other_address = $('#post-other').val();
	var photo = $('#post-photo').val();
	var start_date = $('#post-start').val();
	var end_date = $('#post-end').val();
	var time = $('#post-time').val();
	if($.trim(title) == ''){
		alert('Please enter title');
		$('#post-title').focus();
		return false;
	}else if($.trim(content) == ''){
		alert('Please enter description');
		$('#post-content').focus();
		return false;
	}else if($.trim(other_address) == ''){
		alert('Please enter your address');
		$('#post-other').focus();
		return false;
	}else if($.trim(start_date) == ''){
		alert('Please enter start date');
		$('#post-start').focus();
		return false;
	}else if($.trim(end_date) == ''){
		alert('Please enter end date');
		$('#post-end').focus();
		return false;
	}else if($.trim(time) == ''){
		alert('Please enter time');
		$('#post-time').focus();
		return false;
	}else if($.trim(photo) == ''){
		alert('Please choose a photo');
		$('#post-photo').focus();
		return false;
	}else if($('#post-condition:checked').length == 0){
		alert('Please agree term & condition');
		return false;
	}else{
		var geocoder = new google.maps.Geocoder();
		geocoder.geocode({'address': other_address}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				var lat = results[0].geometry.location.lat();
				var lng = results[0].geometry.location.lng();
				var comps = results[0].address_components;
				console.log(comps)
				for(var j=0;j<comps.length;j++){
					var comp = comps[j].types;
					if(comp[0] == 'postal_code'){
						$('#post-code').val(comps[j].long_name);
					}
					if(comp[0] == 'administrative_area_level_2'){
						$('#post-city').val(comps[j].long_name);
					}
			    }
			    
				$('#post-lat').val(lat);
				$('#post-lng').val(lng);
				$.ajax({
					url: $('#post-form').attr('action'),
					type: 'post',
					data: formData,
					dataType: 'json',
					contentType: false,
					processData:false,
					beforeSend: function(){
						$('#loading').show();
						$('#loading').height($('body').height());
					},
					success: function(data){
						$('#loading').hide();
						if(data == 1){
							alert('Success');
							window.location.reload();
						}else if(data == 2){
							alert('Your photo is too large, please upload photo < 1Mb!!!');
						}else{
							alert('Can not upload photo!!!');
						}
					}
				});
			}else{
				return false;
			}
		});
	}
}

function getCurrentAddress(){
	var geocoder = new google.maps.Geocoder();
  	if (geocoder && navigator.geolocation){
		navigator.geolocation.getCurrentPosition(function(position){
			var lat = position.coords.latitude;
			var lng = position.coords.longitude;
			// $('#post-lat').val(lat);
			// $('#post-lng').val(lng);
		    var latlng = new google.maps.LatLng(lat, lng);
		    var geocoder = new google.maps.Geocoder();
		    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
		        if (status !== google.maps.GeocoderStatus.OK) {
		        	alert(status);
		        }
		        // This is checking to see if the Geoeode Status is OK before proceeding
		        if (status == google.maps.GeocoderStatus.OK) {
		        	var address = (results[0].formatted_address);
		        	$('#post-other').val(address);
		    	}
			});  
		});//, geoLocError, geoLocProgress, {desiredAccuracy:5, maxWait:15000,enableHighAccuracy: true,timeout:15000,maximumAge: Infinity});
	}
}
function datetime(){
	var nowTemp = new Date();
	var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
	if($('#post-start').length){
		var checkin = $('#post-start').datepicker({
						format: 'mm/dd/yyyy',
					  	onRender: function(date) {
							return date.valueOf() < now.valueOf() ? 'disabled' : '';
						}
					}).on('changeDate', function(ev) {
				  		if(ev.date.valueOf() > checkout.date.valueOf()) {
				    		var newDate = new Date(ev.date)
				    		newDate.setDate(newDate.getDate() + 1);
				    		checkout.setValue(newDate);
				  		}
				  		checkin.hide();
				  		$('#post-end')[0].focus();
					}).data('datepicker');
			}
	if($('#post-end').length){
		var checkout = $('#post-end').datepicker({
						format: 'mm/dd/yyyy',
					  	onRender: function(date) {
					    	return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
					  	}
					}).on('changeDate', function(ev) {
				  		checkout.hide();
					}).data('datepicker');
			}
}
function checkMail(sEmail) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (filter.test(sEmail)) {
        return true;
    }
    else {
        return false;
    }
}